//
//  ASColPaginatorController.swift
//  soapp
//
//  Created by zhu xietong on 2018/4/24.
//

import Foundation

import Kingfisher
import JoLoading
import Eelay
import AsyncDisplayKit
import Alamofire

open class ASColPaginatorController: ASColListController,Paginator {
    
    open func pageResponse(task: JoTask?, response: RootData?) {
        
    }
    open var emptyLayerClass:PaginatorEmptyLayer.Type{
        get
        {
            return PaginatorEmptyLayer.defaultClass
        }
    }
    
    open var sections:TP.section{
        get{
            let sec:TP.section = [
                []
            ]
            return sec
        }
    }
    
    open var selector:TP.selector{
        get{
            let sel = TP.selector()
            assertionFailure("Must override selector:TP.selector,\(#file) \(#line)")
            //            alert("Must override selector:TP.selector")
            return sel
        }
    }
    //    public var tableNode:ASTableNode = ASTableNode(style: .plain)
    //    var tableView:UITableView{
    //        get{
    //            return tableNode.view
    //        }
    //    }
    public var so_constraints = [NSLayoutConstraint]()
    
    //    public var page_load_section = "section0"
    
    
    
    required public init() {
        super.init()
    }
    
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    public override func load(sections:TP.section,selector:TP.selector)
    {
        collectionNode.load(sections: sections, selector: selector)
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        let vself = self
        collectionNode.alwaysBounceVertical = true

        vself.pagingScrollView = self.collectionView
        
        self.view.backgroundColor = UIColor._background
    }
    
    open override func refreshLinkView() {
        reload_page()
    }
    
    open func responesHandle(response:RootData?) {
        
    }
    
    open override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        
        TypeInitController.IDActiveAction(self,actionID,model)
    }
    
    
        override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    open func loadOnePage(list: [Any])->[Any] {
        return list
    }
    
    open func reload_page() {
        loadMore(page: self.paginator.page_begin)
        //            refresh()
//        load(sections: sections, selector: selector)
//        collectionNode.reloadData()
        loadingV.loading()
    }
    
    
    
    
    open func overseverListLoad(page:Int,sectionList:NSMutableArray)
    {
        if page == self.paginator.page_begin
        {
            sectionList.removeAllObjects()
            loadingV.dismiss()
        }
    }
    
    open func reloadSections()
    {
        
    }
    
    
    open func willPlayupPageSection()//将要渲染分页数据
    {
        
    }

    
    
    //注意以下方法override 只能写在
    open func load(page: Int, succeed: Bool, list: [Any], response: RootData?, status: PageDataStatus, scrollView: UIScrollView) {
        if page == paginator.page_begin
        {
            load(sections: sections, selector: selector)
            reloadSections()
        }
        
        let _list = self.loadOnePage(list: list)
 
        if let collectionV = scrollView as? UICollectionView
        {
            collectionV.backgroundView = nil
            if succeed
            {
                if let items = collectionNode.model[obj:"\(page_load_section)",nil] as? NSMutableArray
                {
                    self.overseverListLoad(page: page, sectionList: items)
                    var count = items.count
                    var ps = [IndexPath]()
                    let section = sectionIndex
                    for _ in _list
                    {
                        let v = IndexPath(row: count, section: section)
                        ps.append(v)
                        count = count + 1
                    }
                    
                    items.addObjects(from: _list)
                    willPlayupPageSection()
                    switch status{
                    case .empty:
                        collectionV.backgroundView = emptyLayer
                        emptyLayer.emptyMessage = paginator.empty_msg
                     
                    case .err(let msg):
                        print("loadListErr|\(msg)")
                    default:
                        break
                    }
                    
                    self.responesHandle(response: response)
                    if page == self.paginator.page_begin
                    {
                        reloadDataActionHappensHere()
                    }
                    else
                    {
                        
                        //                        self.tableNode.reloadData()
                        //                        tableNode.waitUntilAllUpdatesAreProcessed()
                        
                        collectionNode.insertItems(at: ps)
//                        collectionNode.insertRows(at: ps, with: .top)
                    }
                }
            }
            else{
                if page == self.paginator.page_begin
                {
                    self.loadingV.alertResult(result: self.paginator.net.resultTip)

//                    self.mo_request_alert(msg: "请检查网络链接是否正常".loc)
                }
            }
        }
    }
    
    open func pageRequest()
    {
        
        self.paginator.page = self.paginator.page + 1
        if paginator.page == PageConfig.page_begin
        {
            self.pagingScrollView.mj_footer?.endRefreshingWithNoMoreData()
        }
    
        if self.paginator.in_test
        {
            self.testPageRequest()
        }
        else
        {
            self.netPageRequest()
        }
        
    }
    
    
   
    open override func mo_request_alert
        (
        msg:String = "请检查网络链接是否正常".loc,
        title:String = "".loc,
        bt_title:String = "".loc
        )
    {
        weak var wself = self
        self.loadingV.handle(message: msg, title: title, button: bt_title, handAction: {
            wself?.reload_page()
            switch bt_title.escapeHeadTailSpace(){
            case "登录".loc,"立即登录".loc:
                EeAuthControl.getUser(finish_block: { (success, msg, user) in
                    
                })
            case "重试".loc,"刷新".loc:
                wself?.reload_page()
            default:
                wself?.reload_page()
            }
            
            
            //            wself?.loadingV.loading()
            //            wself?.loadMore(page: PageConfig.page_begin,justNow: true)
            //            wself?.refresh()
        })
        
    }

    
    
    deinit {
        self.paginator.net.cancel()
        if TypeInitController.autoClearMemoryCache
        {
            KingfisherManager.shared.cache.clearMemoryCache()
        }
        
    }
    
    
}




